package com.didd.core.common.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt-token 加、解密工具类
 * @author diddd
 */
public class JwtUtil {

    /**
     * 生成永久有效的jwt token
     * @param subject 主题
     * @param secretKey 密钥
     * @return jwt
     */
    public static String createJWT(String subject, String secretKey) {
        return JwtUtil.createJWT(subject, null, secretKey);
    }

    /**
     * 生成会失败的jwt token
     * @param subject 主题
     * @param ttlMillis 失效时间
     * @param secretKey 密钥
     * @return jwt
     */
    public static String createJWT(String subject, Long ttlMillis, String secretKey) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder builder = Jwts.builder()
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS256, secretKey);
        if (ttlMillis != null) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解析jwt token
     * @param compactJws 解析的jwt
     * @param secretKey 密钥
     * @return Claims
     */
    public static Claims parseJWT(String compactJws, String secretKey) {
        Jwts.parser().isSigned(compactJws);
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(compactJws).getBody();
        return claims;
    }

}
